package main

import "fmt"

/*
  责任链模式
  为请求创建了一个接收者对象的链。处理请求的对象是一系列链条，或者一个集合。
  每个处理节点都保存有其他处理节点的引用。接收到请求的时候，会判断该请求是否需要自己处理，处理完毕传给下一个处理节点，有点像流水线作业。
  例子
  用一个map来保存处理器的引用
  单机情况下模拟一个Request的发送
*/

//请求
type Values map[string][]string
type Request struct {
	Method string
	Url string
	PostForm Values
}

//设置参数
func (r *Request) SetValues(key string, values []string)  {
	r.PostForm[key] = append(r.PostForm[key],values...)
}

func (r *Request) Post(url string,mux *Mux)  {
	r.Method = "POST"
	r.Url = url
	SentRequest(r,mux)
}

func SentRequest(r *Request,mux *Mux)  {
	mux.root.Process(r)
}

func NewRequest() *Request  {
	r := Request{}
	r.PostForm = make(Values)
	return &r
}

//请求处理方法
type handlerFunc func(request *Request)
//处理接口
type  IProcess interface {
	Process(request *Request)
}


//制造者
type Processer struct {
	Handlers map[string]IProcess
}

func (p *Processer) SetHandler(key string, process IProcess)  {
   p.Handlers[key] = process
}

type RootProcesser struct {
	Processer
}

func (r RootProcesser) Process(request *Request)  {
	r.Handlers[request.Method].Process(request)
}

func NewRootProcesser() *RootProcesser {
	root := new(RootProcesser)
	handlers := make(map[string]IProcess)
	root.Handlers = handlers
	return root
}

type PostProcesser struct {
	Processer
	Pmux *Mux
}

func (p *PostProcesser) Process(request *Request)  {
     p.Pmux.mux[request.Url](request)
}

func NewPostProcesser(mux *Mux) *PostProcesser {
	post := &PostProcesser{}
	post.Pmux =mux
	post.Handlers = make(map[string]IProcess)
	return post
}

type Mux struct {
	mux map[string]handlerFunc
	root IProcess
}

func (m *Mux) Handle(url string,handlerFunc handlerFunc)  {
	m.mux[url] = handlerFunc
}

func (m *Mux) SetRoot(root IProcess)  {
	m.root = root
}

func NewMux() *Mux  {
	mux := Mux{}
	mux.mux = make(map[string]handlerFunc)
	root := NewRootProcesser()
	post := NewPostProcesser(&mux)
	root.SetHandler("POST",post)
	mux.root = root
	return &mux
}



func main() {
	mux := NewMux()

	mux.Handle("login", func(request *Request) {
		username := request.PostForm["username"][0]
		password := request.PostForm["password"][0]
		fmt.Println(username)
		fmt.Println(password)
	})

	req := NewRequest()
	req.Method="POST"
	req.SetValues("username",[]string{"user1"})
	req.SetValues("password",[]string{"pasw1"})
	req.Post("login",mux)
}
